﻿using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ricebird.Wordprocessing.Extensions
{
    internal static class WordDocumentInternalExtensions
    {
        internal static StyleDefinitionsPart GetOrCreateStyleDefinitionPart(this WordDocument document)
        {
            var doc = document.InternalDocument;
            if (doc.MainDocumentPart.StyleDefinitionsPart == null)
            {
                doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
            }

            if (doc.MainDocumentPart.StyleDefinitionsPart.Styles == null)
            {
                doc.MainDocumentPart.StyleDefinitionsPart.Styles = new Styles();
            }
            return doc.MainDocumentPart.StyleDefinitionsPart;
        }

        internal static Style GetStyleFromDocument(this WordDocument doc, Func<Style, bool> predicate)
        {
            var defPart = doc.GetOrCreateStyleDefinitionPart();
            Style style = defPart.Styles.Descendants<Style>().FirstOrDefault(predicate);
            return style;
        }

        internal static Style GetLinkedStyle (this WordDocument doc, string name)
        {
            var defPart = doc.GetOrCreateStyleDefinitionPart();
            Style style = defPart.Styles.Descendants<Style>().FirstOrDefault(e => e.StyleName.Val == name);

            if (style.LinkedStyle != null)
            {
                string styleId = style.LinkedStyle.Val;
                style = doc.GetStyleFromDocument(e => e.StyleId == styleId);                
            }
            else
            {
                style = null;
            }

            return style;
        }

        internal static void SaveStyle(this WordDocument doc, Style style)
        {
            var defPart = doc.GetOrCreateStyleDefinitionPart();
            Style s = defPart.Styles.Descendants<Style>().FirstOrDefault(e => e.StyleId == style.StyleId);
            if (s == null)
            {
                defPart.Styles.Append(style);
            }
            else
            {
                s = style;
            }
        }
    }
}
